import { phoneNumberReg, specialCharReg, zhReg } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { Button, message } from 'antd';
import type { CreateUserType } from '../types';
import { Role } from '@/utils/types.d';
import { createUser, queryCompanies } from '../service';
import { useRef } from 'react';
import { useState } from 'react';

const defaultRoleOption = [
  {
    value: Role.STAFF,
    label: (
      <div style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
        企业员工
        <small style={{ color: 'gray' }}>
          (只具有查看能力，父级用户可为其任意指定可见停车场或镜像复制其他企业用户的停车场)
        </small>
      </div>
    ),
  },
];
const adminRoleOption = [
  {
    value: Role.ENTERPRISE,
    label: (
      <div>
        企业管理
        <small style={{ color: 'gray' }}>(拥有对子用户和车场设备增删改查的能力)</small>
      </div>
    ),
  },
  ...defaultRoleOption,
];

export default (props: { func: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const formRef = useRef<FormInstance>();
  const userRole = initialState?.currentUser?.role;
  const [targetRole, setTargetRole] = useState<Role | undefined>(
    userRole === Role.ADMIN ? undefined : Role.STAFF,
  );
  const roleOpts = userRole === Role.ADMIN ? adminRoleOption : defaultRoleOption;
  return (
    <ModalForm<CreateUserType>
      title="新建用户"
      layout="horizontal"
      width="40vw"
      formRef={formRef}
      modalProps={{
        destroyOnClose: true,
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建用户
        </Button>
      }
      onValuesChange={(val) => {
        if (val.role !== undefined) setTargetRole(val.role);
      }}
      onFinish={async (values) => {
        const res = await createUser(values);
        setTargetRole(undefined);
        if (res.success) {
          message.success({
            content: res.message,
            key: 'add_user',
          });
          props.func();
          formRef.current?.resetFields();
          return true;
        }
        message.error({
          content: res.message,
          key: 'add_user',
        });
        return false;
      }}
    >
      <ProFormText
        required
        label="用户名称"
        placeholder="请输入用户名称(企业管理员请输入企业名称)"
        name="userName"
        initialValue=""
        rules={[
          {
            validator: (_, val) => {
              if (!val || val.length < 2)
                return Promise.reject(new Error('用户名称长度不得低于2位'));
              if (specialCharReg.test(val))
                return Promise.reject(new Error('用户名称不符合规范，不支持包含特殊字符'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormText
        required
        label="用户账号"
        placeholder="设置账号"
        name="account"
        rules={[
          {
            validator: (_, val) => {
              if (zhReg.test(val) || specialCharReg.test(val))
                return Promise.reject(new Error('用户账号不能含有汉字或特殊字符'));
              if (!val || val.length < 4)
                return Promise.reject(new Error('用户账号长度不得低于4位'));
              return Promise.resolve(val);
            },
          },
        ]}
        initialValue=""
      />
      <ProFormText.Password
        required
        label="登录密码"
        placeholder="设置登录密码"
        name="password"
        initialValue=""
        rules={[
          {
            validator: (_, val) => {
              if (zhReg.test(val)) return Promise.reject(new Error('登录密码不符合要求'));
              if (!val || val.length < 6)
                return Promise.reject(new Error('用户密码长度不得低于6位'));
              if (val === '123456') return Promise.reject(new Error('密码强度过低'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormSelect
        options={roleOpts}
        required
        initialValue={targetRole}
        disabled={userRole !== Role.ADMIN}
        name="role"
        label="用户角色"
        placeholder="请选择当前用户角色"
      />
      <ProFormText
        name="phoneNumber"
        label="手机号码"
        placeholder="请输入手机号"
        rules={[
          {
            validator: (_, val) => {
              if (val && !phoneNumberReg.test(val))
                return Promise.reject(new Error('手机号不符合规范'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      {userRole === Role.ADMIN && targetRole === Role.STAFF && (
        <ProFormSelect
          name="ownerId"
          label="用户归属公司"
          showSearch
          debounceTime={300}
          rules={[{ required: true, message: '请选择用户目标公司' }]}
          placeholder="请选择归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords, false)}
        />
      )}
    </ModalForm>
  );
};
